/*
 * Copyright 2011 Daniel Drown
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * config.c - configuration settings
 */

#include <string.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <limits.h>
#include <errno.h>
#include <unistd.h>

#include <cutils/config_utils.h>

#include "config.h"
#include "dns64.h"
#include "dhcpcd-files/memory.h"
#include "logging.h"
#include "getaddr.h"

struct clat_config config;

/* function: config_item_str
 * locates the config item and returns the pointer to a string, or NULL on failure.  Caller frees pointer
 * root       - parsed configuration
 * item_name  - name of config item to locate
 * defaultvar - value to use if config item isn't present
 */
char *config_item_str(cnode *root, const char *item_name, const char *defaultvar) {
  const char *tmp;

  if(!(tmp = config_str(root, item_name, defaultvar))) {
    logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
    return NULL;
  }
  return strdup(tmp);
}

/* function: config_item_long
 * locates the config item and returns the pointer to a long int, or NULL on failure.  Caller frees pointer
 * root       - parsed configuration
 * item_name  - name of config item to locate
 * defaultvar - value to use if config item isn't present
 */
long int *config_item_long(cnode *root, const char *item_name, const char *defaultvar) {
  const char *tmp;
  char *endptr;
  long int *conf_int;

  conf_int = xmalloc(sizeof(long int));

  if(!(tmp = config_str(root, item_name, defaultvar))) {
    logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
    free(conf_int);
    return NULL;
  }
  *conf_int = strtol(tmp,&endptr,10);
  if(
      ((*conf_int == LONG_MIN || *conf_int == LONG_MAX) && (errno > 0))
      || (*conf_int == 0 && errno > 0)
      ) {
    perror("strtol");
    free(conf_int);
    return NULL;
  }
  if(endptr == tmp || *tmp == '\0') {
    logmsg(ANDROID_LOG_FATAL,"%s config item is not numeric: %s",item_name,tmp);
    free(conf_int);
    return NULL;
  }
  if(*endptr != '\0') {
    logmsg(ANDROID_LOG_FATAL,"%s config item contains non-numeric characters: %s",item_name,endptr);
    free(conf_int);
    return NULL;
  }
  return conf_int;
}

/* function: config_item_ip
 * locates the config item and returns the pointer to a parsed ip address, or NULL on failure.  Caller frees pointer
 * root       - parsed configuration
 * item_name  - name of config item to locate
 * defaultvar - value to use if config item isn't present
 */
struct in_addr *config_item_ip(cnode *root, const char *item_name, const char *defaultvar) {
  const char *tmp;
  struct in_addr *retval;
  int status;

  retval = xmalloc(sizeof(struct in_addr));

  if(!(tmp = config_str(root, item_name, defaultvar))) {
    logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
    free(retval);
    return NULL;
  }

  status = inet_pton(AF_INET, tmp, retval);
  if(status <= 0) {
    logmsg(ANDROID_LOG_FATAL,"invalid IPv4 address specified for %s: %s", item_name, tmp);
    free(retval);
    return NULL;
  }

  return retval;
}

/* function: config_item_ip6
 * locates the config item and returns the pointer to a parsed ipv6 address, or NULL on failure.  Caller frees pointer
 * root       - parsed configuration
 * item_name  - name of config item to locate
 * defaultvar - value to use if config item isn't present
 */
struct in6_addr *config_item_ip6(cnode *root, const char *item_name, const char *defaultvar) {
  const char *tmp;
  struct in6_addr *retval;
  int status;

  retval = xmalloc(sizeof(struct in6_addr));

  if(!(tmp = config_str(root, item_name, defaultvar))) {
    logmsg(ANDROID_LOG_FATAL,"%s config item needed",item_name);
    free(retval);
    return NULL;
  }

  status = inet_pton(AF_INET6, tmp, retval);
  if(status <= 0) {
    logmsg(ANDROID_LOG_FATAL,"invalid IPv6 address specified for %s: %s", item_name, tmp);
    free(retval);
    return NULL;
  }

  return retval;
}

/* function: free_config
 * frees the memory used by the global config variable
 */
void free_config() {
  // no memory dynamically allocated
}

/* function: dns64_detection
 * does dns lookups to set the plat subnet or exits on failure
 */
void dns64_detection() {
  char *ipv4_hostnames[] = {"ipv4.google.com","ipv4.t-mobile.com"};
  int i, backoff_sleep;
  struct in6_addr *tmp_ptr;

  backoff_sleep = 1;

  while(1) {
    for(i = 0; i < sizeof(ipv4_hostnames)/sizeof(char *); i++) {
      tmp_ptr = plat_prefix(ipv4_hostnames[i]);
      if(tmp_ptr) {
        memcpy(&config.plat_subnet, tmp_ptr, sizeof(struct in6_addr));
        free(tmp_ptr);
        return;
      }
    }
    logmsg(ANDROID_LOG_WARN, "dns64_detection failed, sleeping for %d seconds", backoff_sleep);
    sleep(backoff_sleep);
    if(backoff_sleep >= 120) {
      backoff_sleep = 120;
    } else {
      backoff_sleep *= 2;
    }
  }
}

int subnet_from_interface(cnode *root, const char *interface) {
  union anyip *interface_ip;
  struct in6_addr *mask, *bits;
  int i;

  interface_ip = getinterface_ip(interface, AF_INET6);
  if(!interface_ip) {
    logmsg(ANDROID_LOG_FATAL,"unable to find an ipv6 ip on interface %s",interface);
    return 0;
  }

  memcpy(&config.ipv6_local_subnet, &interface_ip->ip6, sizeof(struct in6_addr));
  free(interface_ip);

  if(!(mask = config_item_ip6(root, "ipv6_local_mask", "::ffff:0:0:0"))) {
    return 0;
  }
  if(!(bits = config_item_ip6(root, "ipv6_local_bits", "::abcd:0:0:0"))) {
    free(mask);
    return 0;
  }

  for(i = 0; i < 4; i++) {
    config.ipv6_local_subnet.s6_addr32[i] = 
      (config.ipv6_local_subnet.s6_addr32[i] & ~mask->s6_addr32[i]) |
      (bits->s6_addr32[i] & mask->s6_addr32[i]);
  }

  config.ipv6_local_subnet.s6_addr32[3] &= 0xffffff00; // network address of the /112

  free(mask);
  free(bits);

  return 1;
}

/* function: read_config
 * reads the config file and parses it into the global variable config. returns 0 on failure, 1 on success
 * file - filename to parse
 */
int read_config(const char *file) {
  cnode *root = config_node("", "");
  long int *tmp_int = NULL;
  void *tmp_ptr = NULL;

  if(!root) {
    logmsg(ANDROID_LOG_FATAL,"out of memory");
    return 0;
  }

  memset(&config, '\0', sizeof(config));
  
  config_load_file(root, file);
  if(root->first_child == NULL) {
    logmsg(ANDROID_LOG_FATAL,"Could not read config file %s", file);
    goto failed;
  }


  if(!(tmp_int = config_item_long(root, "mtu", "1500")))
    goto failed;
  config.mtu = *tmp_int;
  free(tmp_int);

  if(!(tmp_int = config_item_long(root, "ipv4mtu", NULL)))
    goto failed;
  config.ipv4mtu = *tmp_int;
  free(tmp_int);

  if((tmp_ptr = (void *)config_str(root, "ipv6_local_subnet_interface", NULL))) {
    if(!subnet_from_interface(root,tmp_ptr))
      goto failed;
  } else {
    if(!(tmp_ptr = config_item_ip6(root, "ipv6_local_subnet", NULL)))
      goto failed;
    memcpy(&config.ipv6_local_subnet, tmp_ptr, sizeof(struct in6_addr));
    free(tmp_ptr);
  }

  if(!(tmp_ptr = config_item_ip(root, "ipv4_local_subnet", "10.255.255.0")))
    goto failed;
  memcpy(&config.ipv4_local_subnet, tmp_ptr, sizeof(struct in_addr));
  free(tmp_ptr);

  tmp_ptr = (void *)config_str(root, "plat_from_dns64", "no");
  if(!tmp_ptr || strcmp(tmp_ptr, "no") == 0) {
    if(!(tmp_ptr = config_item_ip6(root, "plat_subnet", NULL)))
      goto failed;
    memcpy(&config.plat_subnet, tmp_ptr, sizeof(struct in6_addr));
    free(tmp_ptr);
  } else {
    dns64_detection();
  }

  return 1;

failed:
  free(root);
  free_config();
  return 0;
}

/* function; dump_config
 * prints the current config
 */
void dump_config() {
  char charbuffer[INET6_ADDRSTRLEN];

  logmsg(ANDROID_LOG_DEBUG,"mtu = %d",config.mtu);
  logmsg(ANDROID_LOG_DEBUG,"ipv4mtu = %d",config.ipv4mtu);
  logmsg(ANDROID_LOG_DEBUG,"ipv6_local_subnet = %s",inet_ntop(AF_INET6, &config.ipv6_local_subnet, charbuffer, sizeof(charbuffer)));
  logmsg(ANDROID_LOG_DEBUG,"ipv4_local_subnet = %s",inet_ntop(AF_INET, &config.ipv4_local_subnet, charbuffer, sizeof(charbuffer)));
  logmsg(ANDROID_LOG_DEBUG,"plat_subnet = %s",inet_ntop(AF_INET6, &config.plat_subnet, charbuffer, sizeof(charbuffer)));
}
